const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_NOT_EXISTS,
  PASSWORD_IS_INCORRENT,
  UNAUTHORIZATION,
} = require("../config/error");
const jwt = require("jsonwebtoken");
const { PUBLIC_KEY } = require("../config/secret");
const userService = require("../service/user.service");
const md5password = require("../utils/md5-password");

const verifyLogin = async (ctx, next) => {
  const { username, password } = ctx.request.body;
  //1.判断用户名密码是否为空
  if (!username || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
  }
  //2.判断该用户在数据库中是否存在

  const users = await userService.findUserByName(username);
  const user = users[0];
  if (!user) {
    return ctx.app.emit("error", NAME_IS_NOT_EXISTS, ctx);
  }
  console.log(md5password(password));
  //3.判断数据库中密码和数据库传递的密码是否一致
  if (user.password !== password) {
    return ctx.app.emit("error", PASSWORD_IS_INCORRENT, ctx);
  }
  //4.将用户信息放到ctx中
  ctx.user = user;
  await next();
};

const verifyAuth = async (ctx, next) => {
  //1.获取token
  const anthorization = ctx.headers.authorization;
  console.log("verifyAuth", anthorization);
  if (!anthorization) {
    return ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
  const token = anthorization.replace("Bearer ", "");
  //2.验证token是否有效
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    ctx.user = result;
    await next();
  } catch (error) {
    console.log(error);
    return ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
};

module.exports = { verifyLogin, verifyAuth };
